package com.p2p.base.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.p2p.base.dao.SequenceDao;
import com.p2p.base.service.SequenceService;

/**
 * leiwen@yiqihao.com
 */
@Service("sequenceService")
public class SequenceServiceImpl implements SequenceService {
	@Resource
	private SequenceDao sequenceDao;

	// 强行开启一个新的事务
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public Long getNextBySequenceName(String sequenceName) {
		Long cur = sequenceDao.getCurrentValue(sequenceName);
		sequenceDao.update(sequenceName);
		Long next = cur + 1;
		return next;
	}

	// 强行开启一个新的事务
	@Transactional( propagation = Propagation.REQUIRES_NEW)
	public Long getNextBySequenceName(String sequenceName, Long maxId) {
		Long cur = sequenceDao.getCurrentValue(sequenceName);
		sequenceDao.update(sequenceName);
		Long next = cur + 1;
		if (next > maxId) {
			sequenceDao.reset(sequenceName);
			return 1L;
		}
		return next;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public Long getBorrowerBySequenceName(String name) {
		Long cur = sequenceDao.getCurrentValue(name);
		sequenceDao.update(name);
		Long next = cur + 1;
		return next;
	}
}
